package com.atguigu.app.dws.is_new;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.Func.MyWindowFunction;
import com.atguigu.bean.TrafficOnePageInSessionBean;
import com.atguigu.util.ClickHouseUtil_hjy;
import com.atguigu.util.MyKafkaUtil_hjy;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.TimestampAssignerSupplier;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.IterativeCondition;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * @author hjy
 * @create 2023/3/28 10:22
 */
public class Dws_TrafficIsNewOnePageINSession {
    public static void main(String[] args) throws Exception {
        //todo 1 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://47.102.112.46:8020/gmall-flink/check/baseLogApp");
//        env.getCheckpointConfig().setCheckpointTimeout(60000L);
//        env.setStateBackend(new HashMapStateBackend());
//        System.setProperty("HADOOP_USER_NAME","atguigu");
        //todo 2 从kafka主题（dwd_traffic_page_log）消费数据
        String topic = "dwd_traffic_page_log";
        String groupId = "dws_traffic_vc_ch_ar_isNew_pageView_window";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil_hjy.getKafkaConsumer(topic, groupId));
        //todo 3 将数据转为JSONObj 并过滤 并提取时间戳
        SingleOutputStreamOperator<JSONObject> jsonObjWithWM = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                JSONObject record = JSON.parseObject(value);
                if (record.getString("page") != null) {
                    out.collect(record);
                }
            }
        })
                .assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                        .withTimestampAssigner(TimestampAssignerSupplier.of(new SerializableTimestampAssigner<JSONObject>() {
                            @Override
                            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                                return element.getLong("ts");
                            }
                        })));
        //todo 4 按照mid分组
        KeyedStream<JSONObject, String> keyedStream = jsonObjWithWM.keyBy(value -> value.getJSONObject("common").getString("mid"));

        //todo 5 cep求跳出会话
        Pattern<JSONObject, JSONObject> patten = Pattern.<JSONObject>begin("onePage")
                .where(new IterativeCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject value, Context<JSONObject> ctx) throws Exception {
                        return value.getJSONObject("page").getString("last_page_id") == null;
                    }
                })
                .next("other_session")
                .where(new IterativeCondition<JSONObject>() {
                           @Override
                           public boolean filter(JSONObject value, Context<JSONObject> ctx) throws Exception {
                               return value.getJSONObject("page").getString("last_page_id") == null;
                           }
                       }
                )
                //认为20秒没有下一个就超时
               .within(Time.seconds(20));
        //todo 6 cep匹配
        PatternStream<JSONObject> patternStream = CEP.pattern(keyedStream, patten);
        //todo 7 转为javaBean 并输出流
        SingleOutputStreamOperator<TrafficOnePageInSessionBean> cepStream = patternStream.select(new OutputTag<TrafficOnePageInSessionBean>("out"){}, new PatternTimeoutFunction<JSONObject, TrafficOnePageInSessionBean>() {
            @Override
            public TrafficOnePageInSessionBean timeout(Map<String, List<JSONObject>> pattern, long timeoutTimestamp) throws Exception {
                List<JSONObject> onePage = pattern.get("onePage");
                JSONObject value = onePage.get(0);
                JSONObject common = value.getJSONObject("common");
                return TrafficOnePageInSessionBean.builder()
                        .vc(common.getString("vc"))
                        .ar(common.getString("ar"))
                        .ch(common.getString("ch"))
                        .isNew(common.getString("is_new"))
                        .OneSvCt(1L)
                        .build();
            }
        },new PatternSelectFunction<JSONObject, TrafficOnePageInSessionBean>() {
            @Override
            public TrafficOnePageInSessionBean select(Map<String, List<JSONObject>> pattern) throws Exception {
                List<JSONObject> onePage = pattern.get("onePage");
                JSONObject value = onePage.get(0);
                JSONObject common = value.getJSONObject("common");
                return TrafficOnePageInSessionBean.builder()
                        .vc(common.getString("vc"))
                        .ar(common.getString("ar"))
                        .ch(common.getString("ch"))
                        .isNew(common.getString("is_new"))
                        .OneSvCt(1L)
                        .build();
            }
        });
        //todo 8 合并两个流
        DataStream<TrafficOnePageInSessionBean> outDS = cepStream.getSideOutput(new OutputTag<TrafficOnePageInSessionBean>("out"){});
        DataStream<TrafficOnePageInSessionBean> unionDS = cepStream.union(outDS);

        //todo 8 按照ch分组
        KeyedStream<TrafficOnePageInSessionBean, String> keyedByChDS = unionDS.keyBy(TrafficOnePageInSessionBean::getIsNew);

        //todo 9 开窗聚合
        SingleOutputStreamOperator<TrafficOnePageInSessionBean> reduceDS = keyedByChDS
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<TrafficOnePageInSessionBean>() {
                    @Override
                    public TrafficOnePageInSessionBean reduce(TrafficOnePageInSessionBean value1, TrafficOnePageInSessionBean value2) throws Exception {
                        value1.setOneSvCt(value1.getOneSvCt() + value2.getOneSvCt());
                        return value1;
                    }
                }, new WindowFunction<TrafficOnePageInSessionBean, TrafficOnePageInSessionBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<TrafficOnePageInSessionBean> input, Collector<TrafficOnePageInSessionBean> out) throws Exception {
                        TrafficOnePageInSessionBean next = input.iterator().next();
                        out.collect(MyWindowFunction.getWindow(next, window));
                    }
                });

        //todo 10 写出数据到clickHouse
        reduceDS.print("reduceDS>>>>>>>>>>>");
        reduceDS.addSink(ClickHouseUtil_hjy.getClickHouseSink("insert into dws_traffic_isNew_onePage_window values(?,?,?,?,?,?,?,?)"));

        //todo 11 启动程序
        env.execute();


    }
}
